<%@ page language="java" import="java.util.*"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<%@include file="/common/common.jsp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<base href="<%=basePath%>">
		<title>Flexible EE Page</title>
		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
		<meta http-equiv="description" content="This is my page">
		<link rel="stylesheet" type="text/css" href="common/css/complex.css" />
		<link type="text/css" rel="stylesheet" href="themes/smoothness/jquery-ui-1.8.7.custom.css" />
		<link type="text/css" rel="stylesheet" href="script/jqGrid3.8/css/ui.jqgrid.css" />
		<link type="text/css" rel="stylesheet" href="script/jqGrid3.8/css/ui.multiselect.css" />
		
		<style type="text/css">

body {
	overflow: hidden;
	font-family: Verdana, Arial, Helvetica, sans-serif;
	background-color: #EEE;
	font-size: 0.625em;
}

#loading {
        position: absolute;
        width: 100%;
        height: 100%;
        text-align: center;
        padding: 300px 0 0 0;
        font: bold 16px Arial, Helvetica, sans-serif;
		background-color: #ffffff;
		color: #3399ff;
		z-index: 9999;
    }
/**
		 * overwrite jQueryUI CSS Starts
		 */
.ui-state-active,.ui-widget-content .ui-state-active,.ui-widget-header .ui-state-active
{
	BORDER: #afafaf 1px solid;
	BACKGROUND: url(common/img/nav_bg.gif) repeat-x;
	COLOR: #2c2b2b;
	FONT-WEIGHT: bold;
	height: 25px;
}

.ui-state-default,.ui-widget-content .ui-state-default,.ui-widget-header .ui-state-default
{
	color: #336699
}

.ui-widget-content {
	color: #336699
}

.ui-widget-overlay {
	background: #aaaaaa url(common/img/overlay.png) 50% 50% repeat;
}

.ui-widget-shadow {
	margin: -8px 0 0 -8px;
	padding: 8px;
	background: #aaaaaa url(common/img/overlay.png) 50% 50% repeat-x;
}

/* main item style*/
.main-item {
	margin: 0 0 5px 0;
}

.item-header {
	BACKGROUND: url(common/img/panel_bg.gif) #f8f8f8 repeat-x;
	height: 22px;
	color: #336699;
	cursor: move;
	padding: 0.375em 0.2em 0.2em 0.375em;
	line-height: 22px;
}

.item-header .ui-icon {
	float: right;
	cursor: pointer;
}

.item-content {
	color: #336699;
	padding: 0.375em;
}

.header {
	BACKGROUND: url(common/img/panel_bg.gif) #f8f8f8 repeat-x;
	color: #336699;
	border-bottom: 1px solid #777;
	padding: 2px 0 4px;
	text-align: center;
	line-height: 22px;
	position: relative;
	overflow: hidden;
}

.footer {
	background: #718ba6;
	padding: 3px 10px;
	height: 28px;
	position: relative;
	overflow: hidden;
	color: #fff;
	border-top: 1px solid #777;
	text-align: center;
}

/* accordion item hover style */
.item-hover,.item-click {
	COLOR: #2c2b2b;
	BACKGROUND: #e5f1fa;
	border: 1px solid #afafaf
}

/* accordion category action style */
#saveOrderIcon {
	cursor: pointer;
	margin-right: 18px;
	margin-top: 5px;
	position: absolute;
	width: 16px;
	height: 16px;
	right: 10px;
	top: 0px
}

#accordions h3 span {
	float: right;
	display: none;
}

/* accordion items action style */
#accordions li span {
	float: left;
}

#accordions li a {
	float: right;
	display: none;
}

/* sortable accordion items */
.connectedSortable li,.sysFilterItems li {
	color: #336699;
	margin: 0;
	FONT-SIZE: 10px; *FONT-SIZE: 10px; _FONT-SIZE: 10px;
	height: 18px;
	padding: 10px 15px;
}

.ui-sortable-placeholder {
	border: 1px dotted red;
	visibility: visible !important;
	height: 20px !important;
}

.ui-sortable-placeholder * {
	visibility: hidden;
}

.ui-sortable-placeholder-item {
	border: 1px dotted blue;
	visibility: visible !important;
	height: 20px !important;
}

.ui-sortable-placeholder-item * {
	visibility: hidden;
}

/* edit Accordion Item */
#sysIcons .ui-selecting {
	background: #FECA40;
}

#sysIcons .ui-selected {
	background: #F39814;
	color: white;
}

#sysIcons {
	list-style-type: none;
	margin: 0;
	padding: 0;
}

#sysIcons li {
	margin: 3px;
	padding: 1px;
	float: left;
	width: 35px;
	height: 35px;
	font-size: 1.4em;
	text-align: center;
	vertical-align: middle;
}

		/* Log style */
		.failureLog { color: red }
		.successLog { color: green }


</style>

		<script type="text/javascript" src="script/jquery-1.4.4.min.js"></script>
		<script type="text/javascript" src="script/jquery-ui-1.8.7.custom.min.js"></script>
		<script type="text/javascript" src="script/utils/jquery.cookie.min.js"></script>
		<script type="text/javascript" src="script/utils/json2.min.js"></script>

		<script type="text/javascript" src="script/jqGrid3.8/js/i18n/grid.locale-en.js"></script>
		<script type="text/javascript" src="script/jqGrid3.8/plugins/ui.multiselect.js"></script>
		<script type="text/javascript" src="script/jqGrid3.8/jquery.jqGrid.min.js"></script>
		<script type="text/javascript" src="script/jqGrid3.8/plugins/grid.postext.js"></script>

		<script type="text/javascript" src="script/ui-layout/jquery.layout-latest.js"></script>
		<script type="text/javascript" src="script/ui-layout/complex.js"></script>
		<script type="text/javascript" src="script/validate/jquery.validate.js"></script>

		<script language="JavaScript" type="text/javascript">
	
		jQuery(window).load(function(){$("#loading").hide();});
		
	<c:choose>
		<c:when test="${empty wrapper.id}">
			var cfgId = 0;
		</c:when>
		<c:otherwise>
			var cfgId = <c:out value="${wrapper.id}" />;
		</c:otherwise>
	</c:choose>

	var outerLayout, gridPerm;
	var layoutSettings = {
		name : "outerLayout",
		defaults : {
			size : "auto"
			//                ,       minSize:                                80
			,
			paneClass : "pane" // default = 'ui-layout-pane'
			,
			resizerClass : "resizer" // default = 'ui-layout-resizer'
			,
			togglerClass : "toggler" // default = 'ui-layout-toggler'
			,
			buttonClass : "button" // default = 'ui-layout-button'
			,
			contentSelector : ".content" // inner div to auto-size so only it scrolls, not the entire pane!
			,
			contentIgnoreSelector : "span" // 'paneSelector' for content to 'ignore' when measuring room for content
			,
			togglerLength_open : 35 // WIDTH of toggler on north/south edges - HEIGHT on east/west edges
			,
			togglerLength_closed : 35 // "100%" OR -1 = full height
			,
			hideTogglerOnSlide : true // hide the toggler when pane is 'slid open'
			,
			togglerTip_open : "Close This Pane",
			togglerTip_closed : "Open This Pane",
			resizerTip : "Resize This Pane",
			fxName : "slide" // none, slide, drop, scale
			,
			fxSpeed_open : 750,
			fxSpeed_close : 1500,
			fxSettings_open : {
				easing : "easeInQuint"
			},
			fxSettings_close : {
				easing : "easeOutQuint"
			}
		},
		north : {
			spacing_open : 0 // cosmetic spacing
			,
			togglerLength_open : 0 // HIDE the toggler button
			,
			togglerLength_closed : -1 // "100%" OR -1 = full width of pane
			//                ,		spacing_closed: 0								//either (togglerLength_closed & spacing_closed) eq 0 is hide the toggler button
			//                ,       slidable:                               false
			//      override default effect
			,
			fxName :                                 "none"
                }
        ,       south: {
			//                        size:                                27
			//                ,       spacing_closed:                 10                       // HIDE resizer & toggler when 'closed'
			//                ,       slidable:                               true           // REFERENCE - cannot slide if spacing_closed = 0
			resizable : false,
			togglerLength_open : -1,
			togglerLength_closed : -1 // "100%" OR -1 = full width of pane
			,
			fxName : "none",
			onclose : function() {
				jQuery("#jqGrid")
						.jqGrid(
								"setGridHeight",
								$("#mainContent").height()
										- $("#p3").outerHeight(true)
										- $("#p4 .item-header").outerHeight(
												true) - 118);
			},
			onopen : function() {
				jQuery("#jqGrid")
						.jqGrid(
								"setGridHeight",
								$("#mainContent").height()
										- $("#p3").outerHeight(true)
										- $("#p4 .item-header").outerHeight(
												true) - 118);
			}
		},
		west : {
			size : 200,
			spacing_closed : 8 // wider space when closed
			,
			togglerAlign_closed : "center" // align to center of resizer
			,
			togglerLength_closed : 48 // make toggler 'square' - 21x21
			,
			togglerLength_open : 48 // toggler button size when status is opened
			,
			togglerTip_open : "Close West Pane",
			togglerTip_closed : "Open West Pane",
			resizerTip_open : "Resize West Pane",
			slideTrigger_open : "click" // default
			,
			initClosed : false
			//      add 'bounce' option to default 'slide' effect
			,
			fxSettings_open : {
				easing : "easeOutBounce"
			},
			onresize : function() {
				$("#accordions").accordion("resize");
			},
			onclose : function() {
				jQuery("#jqGrid").jqGrid("setGridWidth", $("#p4").width() - 10);
			},
			onopen : function() {
				jQuery("#jqGrid").jqGrid("setGridWidth", $("#p4").width() - 10);
			}
		},
		east : {
			size : 90,
			maxSize : 150,
			spacing_closed : 6 // wider space when closed
			,
			togglerLength_closed : 48 // make toggler 'square' - 21x21
			,
			togglerAlign_closed : "center",
			togglerLength_open : 48,
			slideTrigger_open : "mouseover",
			initClosed : false
			//      override default effect, speed, and settings
			,
			fxName : "drop",
			fxSpeed : "normal",
			fxSettings : {
				easing : ""
			}
		// nullify default easing
		},
		center : {
			paneSelector : "#mainContent" // sample: use an ID to select pane instead of a class
		}
	};

	//init layout
	$(document).ready(function() {

		// create the OUTER LAYOUT
		outerLayout = $("body").layout(layoutSettings);

		// save selector strings to vars so we don't have to repeat it
		// must prefix paneClass with "body > " to target ONLY the outerLayout panes
		var westSelector = "body > .ui-layout-west"; // outer-west pane
		var eastSelector = "body > .ui-layout-east"; // outer-east pane

		// CREATE SPANs for pin-buttons - using a generic class as identifiers
		$("<span></span>").addClass("pin-button").prependTo(westSelector);
		$("<span></span>").addClass("pin-button").prependTo(eastSelector);
		// BIND events to pin-buttons to make them functional
		outerLayout.addPinBtn(westSelector + " .pin-button", "west");
		outerLayout.addPinBtn(eastSelector + " .pin-button", "east");

		// CREATE SPANs for close-buttons - using unique IDs as identifiers
		$("<span></span>").attr("id", "west-closer").prependTo(westSelector);
		$("<span></span>").attr("id", "east-closer").prependTo(eastSelector);
		// BIND layout events to close-buttons to make them functional
		outerLayout.addCloseBtn("#west-closer", "west");
		outerLayout.addCloseBtn("#east-closer", "east");

	});

	$(function() {

		// Main page Navigation 

		// ** JS variable
		var filterId;
		var rowData;
		var jqGridCfg;
		var $jqGrid;
		var $treeIds;
		var $accordions;
		var $selectedCategory;
		var $selectedItem;
		var $multiEditor;
		var $sysIcons = $("#sysIcons").selectable();

		// ** restore the order
		var mainItemsSortable = $("#mainContent");
		var order = $.cookie("sortableOrder");

		if (order) {
			$.each(order.split(","), function(i, id) {
				//appending the element with the ID, given id should move each element to the end of the 
				// list one after another, and at the end, the order should be restored.
				$("#" + id).appendTo(mainItemsSortable);
			});
		}
		;

		// ** init variable properties 
		$treeIds = new Object();
		enableTreeCache(true);

		// ** store the item order in cookie
		mainItemsSortable.sortable({
			handle : '.item-header',
			cursor : 'move',
			opacity : 0.4,
			update : function(e, ui) {
				order = mainItemsSortable.sortable("toArray").join();
				$.cookie("sortableOrder", order);
			}

		});

		// ** add show & hide panel
		mainItemsSortable
				.find(".main-item")
				.addClass("ui-widget ui-widget-content ui-helper-clearfix")
				.find(".item-header")
				.addClass("ui-widget-header")
				.prepend(
						'<a href="javascript:void(0)"><span class="ui-icon ui-icon-circle-triangle-n"></span></a>')
				.find("a").hover(function() {
					$(this).addClass('ui-state-hover');
				}, function() {
					$(this).removeClass('ui-state-hover');
				}).find(".ui-icon").click(
						function() {
							$(this).toggleClass("ui-icon-circle-triangle-n")
									.toggleClass("ui-icon-circle-triangle-s");
							$(this).parents(".main-item:first").find(
									".item-content").toggle();
							reCalcGridHeight();
						});

		// ** main center panel end ------------------------

		function addCommas(nStr) {
			nStr += '';
			x = nStr.split('.');
			x1 = x[0];
			x2 = x.length > 1 ? '.' + x[1] : '';
			var rgx = /(\d+)(\d{3})/;
			while (rgx.test(x1)) {
				x1 = x1.replace(rgx, '$1' + ',' + '$2');
			}
			return x1 + x2;
		}

		// ** custom fomatters & editors start -----------------
		function emptyValueFmtter(cellvalue) {
			if (!cellvalue)
				cellvalue = "&nbsp;";
			return cellvalue;
		}
		
		function standardFmtter(cellvalue, options, rowObject) {
			if(rowObject['_' + options.colModel.name]) {
				cellvalue = rowObject['_' + options.colModel.name];
			}
			
			return emptyValueFmtter(cellvalue);
		}
		
		function ccyFmtter(cellvalue, options, rowObject) {
			return addCommas(cellvalue);
		}
		
		function treeIconFmtter(cellvalue, options, rowObject) {

			var treeIcon;
			if (rowObject.umbrellaType == 0) {
				treeIcon = "<span class='ui-icon ui-icon-radio-off' width='13' height='13' />";
			} else {
				if (rowObject.umbrellaType == 1) {
					treeIcon = "<span class='ui-icon ui-icon-triangle-1-e' width='13' height='13' title='" + options.rowId + "'/>";
				} else {
					treeIcon = "<span class='ui-icon ui-icon-radio-off' width='13' height='13' style='margin-left: 20px;'/>";
				}
			}

			return treeIcon;
		}

		function redStarFmtter(cellvalue, options, rowObject) {
			if (rowObject.deadline)
				cellvalue = "<font style='color:red'>*</font>" + cellvalue;

			return emptyValueFmtter(cellvalue);
		}

		function stmtStatusFmtter(cellvalue, options, rowObject) {

			if (rowObject.statementStatus == 68)
				cellvalue = "<img src='common/img/tickg.gif' width='13' height='13'/>";
			else {
				if (rowObject.statementStatus == 500)
					cellvalue = "<div>IP</div>";
				else
					cellvalue = "<img src='common/img/crossg.gif' width='13' height='13'/>";
			}

			return emptyValueFmtter(cellvalue);
		}

		function eventSourceFmtter(cellvalue, options, rowObject) {

			if (rowObject.nonNet)
				cellvalue = "Non-Netted";
			else {
				if (rowObject.eventSource == 0)
					cellvalue = "Net";
				else if (rowObject.eventSource == 4)
					cellvalue = "Auto-Net";
			}

			return emptyValueFmtter(cellvalue);
		}

		function tickImgFmtter(cellvalue, options, rowObject) {

			if (cellvalue)
				cellvalue = "<img src='img/tickg.gif' width='13' height='13'/>";

			return emptyValueFmtter(cellvalue);
		}

		function disputedAgeFmtter(cellvalue, options, rowObject) {

			if (rowObject.disputedValue < 0)
				cellvalue = rowObject.disputeAge;

			return emptyValueFmtter(cellvalue);
		}

		function agrBaseCcyFmtter(cellvalue, options, rowObject) {

			cellvalue = "<font style='color:#CC0000'>" + cellvalue + "</font>";

			return emptyValueFmtter(cellvalue);
		}

		function workFlowStatusFmtter(cellvalue, options, rowObject) {

			if (cellvalue == 68)
				cellvalue = "Approved";
			else if (cellvalue == 69)
				cellvalue = "Amended";
			else if (cellvalue == 70)
				cellvalue = "Amended-Waived";

			return emptyValueFmtter(cellvalue);
		}

		function workflowElem(value, options) {
			var $elem;

			var curUserData = getUserData(rowData.workflowId);
			var fourEyeData = curUserData.fourEyeData;

			if (value == "Approved") {
				$elem = $("<select><option value='68'>Approved</option></select>");
			} else if (value == "Amended") {
				$elem = $("<select><option value='68'>Approved</option><option value='69' selected>Amended</select>");
				if (!fourEyeData.workflowStatus4eyesCheck)
					$elem.attr("disabled", "");

			} else if (value == "Amended-Waived") {
				$elem = $("<select><option value='68'>Approved</option><option value='70' selected>Amended-Waived</select>");
				if (!fourEyeData.workflowStatus4eyesCheck)
					$elem[0].disabled = true;
			}
			editFocusTrigger($elem);
			return $elem[0];

		}

		function workflowValue(elem) {
			return elem.val();
		}

		function callStatusFmtter(cellvalue, options, rowObject) {

			//				if(typeof(cellvalue) == "number")	
			if (!isNaN(cellvalue))
				cellvalue = options.colModel.searchoptions.value[cellvalue];

			//				if(cellvalue == 0) cellvalue = " ";
			//				else if(cellvalue == 65) cellvalue = "Pending Review";
			//				else if(cellvalue == 58) cellvalue = "No Call Required";
			//				else if(cellvalue == 204) cellvalue =  "Waived";
			//				else if(cellvalue == 205) cellvalue = "Completed";
			//				else if(cellvalue == 150) cellvalue =  "------";
			//				else if(cellvalue == 55) cellvalue = "Margin Request Issued";
			//				else if(cellvalue == 56) cellvalue = "Margin Request Confirmed";
			//				else if(cellvalue == 145) cellvalue = "Partial Dispute";
			//				else if(cellvalue == 146) cellvalue = "Full Dispute";
			//				else if(cellvalue == 59) cellvalue = "Margin Request Received";
			//				else if(cellvalue == 149) cellvalue = "Collateral Booked";

			return emptyValueFmtter(cellvalue);
		}

		function callStatusElem(value, options) {

			var curUserData = getUserData(rowData.workflowId);
			var fourEyeData = curUserData.fourEyeData;
			var callStatusData = curUserData.callStatusCollection;

			var selectElem = document.createElement("select");

			for ( var p in callStatusData) {
				if (p) {
					//						console.log(p);
					var option = new Option(callStatusData[p], p);
					selectElem.options.add(option);
					if (value == callStatusData[p]) {
						option.selected = true;
					}
				}
			}
			if (!fourEyeData.callStatus4eyesCheck)
				selectElem.disabled = true;

			if (value == 'Completed') {
				$(selectElem).change(function(event) {
					if (checkCallStatusChanged($(this).val())) {
						$(this).val(205);
					}

				});
			}

			editFocusTrigger($(selectElem));
			return selectElem;
		}

		function callStatusValue(elem) {
			return elem.val();
		}

		function udfStatusFmtter(cellvalue, options, rowObject) {
			if (cellvalue == 0)
				cellvalue = "&nbsp;";
			else if (cellvalue == 496)
				cellvalue = "Sub Request Received";
			else if (cellvalue == 497)
				cellvalue = "Sub Request Made";

			return emptyValueFmtter(cellvalue);
		}

		function agreedAmountElem(value, options) {
			var curUserData = getUserData(rowData.workflowId);
			var fourEyeData = curUserData.fourEyeData;

			var inputElem = document.createElement("input");
			inputElem.type = "text";
			inputElem.value = value;

			if (!fourEyeData.agreedAmount4eyesCheck)
				inputElem.disabled = true;

			editFocusTrigger($(inputElem));
			return inputElem;
		}

		function agreedAmountValue(elem) {
			return elem.val();
		}

		function overwriteElem(value, options) {
			var curUserData = getUserData(rowData.workflowId);
			var fourEyeData = curUserData.fourEyeData;

			var checkBoxElem = document.createElement("input");

			checkBoxElem.type = "checkbox";

			if (value == "true") {
				//checkBoxElem.checked = 'checked';
				checkBoxElem.checked = true;
				
				//IE7 bug
				checkBoxElem.defaultChecked = true;
			}
				
			if (!fourEyeData.overwrite4eyesCheck)
				checkBoxElem.disabled = true;

			editFocusTrigger($(checkBoxElem));
			return checkBoxElem;
		}

		function overwriteValue(elem) {
			//				return elem.val();
			return elem.attr("checked");
		}

		function ctpyExposureValue(elem) {
			return elem.find("input").val();
		}

		function ctpyAmtElem(value, options) {

			var $elem = $("<span/>")
					.append("<input value='" + value + "'/>")
					.prepend(
							"<img src='common/img/edit.gif' width='13' height='13'/>");
			$multiEditor = $elem.find("input");
			$elem.find("img").hover(function() {
				$(this).css("cursor", "pointer");
			}, function() {
				$(this).css("cursor", "move");
			}).click(
					function() {

						$("select[name='originalCurrency']").val(
								getUserData(rowData.workflowId).agrBaseCcy);
						$("select[name='resultCurrency']").val(
								getUserData(rowData.workflowId).agrBaseCcy);
						$("#_originalAmount").val($(this).siblings().val());

						$("#dialog-ccyExchange").dialog('open');

					});

			editFocusTrigger($elem.find("input"));
			return $elem[0];
		}

		function ctpyAmtValue(elem) {
			var umbrellaId;
			var fundEventId = elem.prevObject.parent().attr("id");
			var inputValue = elem.find("input").val();
			$.each($treeIds, function(i, val) {
				if ($.inArray(fundEventId, val) !== -1) {
					umbrellaId = i;
				}
			});

			if (umbrellaId) {
				var umRowData = getRowData(umbrellaId);

				var fundAmts = new Array();
				var fundAmt;
				var fundRowData;
				$treeIds[umbrellaId].each(function(index, elem) {
					fundRowData = getRowData(elem);
					fundAmt = new Object();

					if (fundEventId === elem) {
						fundAmt.amtValue = inputValue;
						fundAmt.changed = true;
					} else {
						fundAmt.amtValue = fundRowData[marginDelvCtpy];
						fundAmt.changed = false;
					}

					fundAmt.currency = fundRowData[currencyId];
					fundAmt.actionId = fundRowData[movementRequiredId];

					fundAmts.push(fundAmt);
				});

				sendAjaxRequest({
					method : 'ctpyAmtChange',
					umbrellaCcy : getUserData(umbrellaId)[agrBaseCcy],
					marketDataId : umRowData[marketDataId],
					umbCcyChange : false,
					fundAmts : JSON.stringify(fundAmts)
				}, function(data) {

				});
			}
			return inputValue;

		}
		function umCtpyAmtElem(value, options) {
			var inputElem = document.createElement("input");
			inputElem.type = "text";
			inputElem.value = value;

			editFocusTrigger($(inputElem));
			return inputElem;
		}

		function umCtpyAmtValue(elem) {
			var inputValue = elem.val();
			var fundEventId = parseInt(elem.prevObject.parent().attr("id"));
			var umbrellaId = getUmbrellaId(fundEventId);

			if (umbrellaId) {
				var umRowData = getRowData(umbrellaId);

				var fundAmts = new Array();
				var fundAmt;
				var fundRowData;
				$
						.each(
								$treeIds[umbrellaId],
								function(index, elem) {
									fundRowData = getRowData(elem);
									fundAmt = new Object();

									if (fundEventId === elem) {
										fundAmt.amtValue = inputValue;
										fundAmt.changed = true;
									} else {
										fundAmt.amtValue = fundRowData["marginDelvCtpyUmbBaseCcy"];
										fundAmt.changed = false;
									}

									fundAmt.currency = getUserData(elem).agrBaseCcy;
									fundAmt.actionId = fundRowData["movementRequiredId"];

									fundAmts.push(fundAmt);
								});

				sendSyncRequest({
					method : 'ctpyAmtChange',
					umbrellaCcy : getUserData(umbrellaId).agrBaseCcy,
					marketDataId : umRowData.marketDataId,
					umbCcyChange : true,
					fundAmts : JSON.stringify(fundAmts)
				}, function(data) {

					$('#' + umbrellaId).addClass("edited");

					setCellManually(umbrellaId, 'marginDelvCtpy', data.totalValue);
					setCellManually(umbrellaId, 'marginDelvCtpyUmbBaseCcy', data.totalValue);
					setCellManually(fundEventId, 'marginDelvCtpy', data.fundValue);

				});
			}
			return inputValue;
		}

		function commentsElem(value, options) {

			var $elem = $("<span/>").append(
					"<textarea cols='25' rows='1' style='overflow-y:auto;'>" + value + "</textarea>")
								.prepend(
					"<img src='common/img/edit.gif' width='13' height='13'/>");
			$multiEditor = $elem.find("textarea");
			$elem.find("img").hover(function() {
				$(this).css("cursor", "pointer");
			}, function() {
				$(this).css("cursor", "move");
			}).click(function() {

				$("#txtComments").val($(this).siblings().val());

				$("#dialog-comments").dialog('open');

			});
			
			editFocusTrigger($elem.find("textarea"));
			return $elem[0];
		}

		function commentsValue(elem) {

			return elem.find("textarea").val();
		}

		function getRowData(workflowId) {
			return $jqGrid.jqGrid("getRowData", workflowId);
		}

		function getUserData(workflowId) {
			return $jqGrid.getGridParam('userData')[workflowId];
		}

		// ** custom fomatters & editors end -----------------

		// ** logic JS Starts ---------------
		function checkCallStatusChanged(value) {
			if (value != 58 && value != 205) {
				alert("The entry can only be changed to 'No Call Required'!");
				return true;
			}
			return false;
		}

		function callStatusChanged(e) {

			var callStatus = this.options[this.selectedIndex].value;

			var agreementId = rowData.agreementId;

			var eventSource = rowData.eventSource;

			var eeInitTab = rowData.eeInitTab;

			var eventDate = rowData.eventDate;
			var historical = rowData.historical;

			var trs = $jqGrid.jqGrid("getRowData");
			if (trs != "" && trs != null) {
				if (eeInitTab == 3 || eeInitTab == 7) {
					for ( var i = 1; i < trs.length; i++) {
						if ((trs[i].historical == historical)
								&& (trs[i].eventDate == eventDate)
								&& (trs[i].agreementId == agreementId)
								&& (trs[i].eeInitTab == eeInitTab)
								&& (trs[i].eventSource == eventSource)
								&& (trs[i].callStatus != callStatus)) {
							trs[i].callStatus = callStatus;
							break;
						}
					}
				}
			}
		}

		// ** logic JS Ends ---------------

		//$jqGrid = jQuery("#jqGrid").jqGrid(${jqCfg});
		$jqGrid = jQuery("#jqGrid")
				.jqGrid(
						{
							"autowidth" : true,
							"cellEdit" : true,
							"cellsubmit" : "clientArray",
							"colModel" : [
									{
										"align" : "Left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : treeIconFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "",
										"label" : " ",
										"name" : "treeIcon",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 40
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "integer",
										"hidden" : true,
										"hidedlg" : true,
										"index" : "",
										"label" : "WorkFlow",
										"name" : "workflowId",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 80
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.extId",
										"label" : "External Id",
										"name" : "externalId",
										"resizable" : true,
										"search" : true,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "text",
										"width" : 65
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "integer",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.id",
										"label" : "Agreement Id",
										"name" : "agreementId",
										"resizable" : true,
										"search" : true,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "text",
										"width" : 40
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "integer",
										"hidden" : true,
										"hidedlg" : false,
										"index" : "",
										"label" : "Movement Required",
										"name" : "movementRequiredId",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "integer",
										"hidden" : true,
										"hidedlg" : false,
										"index" : "",
										"label" : "Dead Line",
										"name" : "deadline",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "integer",
										"hidden" : true,
										"hidedlg" : false,
										"index" : "",
										"label" : "Letter Action",
										"name" : "letterAction",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "eventDate",
										"label" : "Event Date",
										"name" : "eventDate",
										"resizable" : true,
										"search" : true,
										"searchoptions" : {
											"dataInit" : datePick
										},
										"sortable" : true,
										"stype" : "text",
										"width" : 65
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : true,
										"hidedlg" : false,
										"index" : "eventDate",
										"label" : "Event Date (Agreement)",
										"name" : "agreementEventDate",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "integer",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "eventId",
										"label" : "Event ID",
										"name" : "eventId",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 55
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "integer",
										"hidden" : true,
										"hidedlg" : false,
										"index" : "agreementHeader.prinOrgHeader.id",
										"label" : "Principal Id",
										"name" : "principalId",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : redStarFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.prinOrgHeader.orgCode",
										"label" : "Principal",
										"name" : "principalCode",
										"resizable" : true,
										"search" : true,
										"searchoptions" : {
											"dataInit" : autoCompleteRemote
										},
										"sortable" : true,
										"stype" : "text",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "integer",
										"hidden" : true,
										"hidedlg" : false,
										"index" : "agreementHeader.cptyOrgHeader.id",
										"label" : "Counterparty Id",
										"name" : "counterpartyId",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.cptyOrgHeader.shortName",
										"label" : "Counterparty",
										"name" : "counterpartyName",
										"resizable" : true,
										"search" : true,
										"searchoptions" : {
											"dataInit" : autoCompleteRemote
										},
										"sortable" : true,
										"stype" : "text",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.description",
										"label" : "Description",
										"name" : "description",
										"resizable" : true,
										"search" : true,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "text",
										"searchoptions" : {
											"dataInit" : autoComplete
										},
										"width" : 100
									},
									{
										"align" : "Center",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : stmtStatusFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "statement.statementStatus.statusId",
										"label" : "Statement Status",
										"name" : "statementStatus",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 70
									},
									{
										"align" : "left",
										"editable" : true,
										"editoptions" : {
											"custom_element" : workflowElem,
											"custom_value" : workflowValue
										},
										"editrules" : "",
										"edittype" : "custom",
										"formatter" : workFlowStatusFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "workflowStatus",
										"label" : "Workflow Status",
										"name" : "workflowStatus",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 80
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "",
										"label" : "CA",
										"name" : "calcAgent",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 25
									},
									{
										"align" : "left",
										"editable" : true,
										"editoptions" : {
											"custom_element" : callStatusElem,
											"custom_value" : callStatusValue
										},
										"editrules" : "",
										"edittype" : "custom",
										"formatter" : callStatusFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "workflowProc.marginCallStatus",
										"label" : "Call Status",
										"name" : "marginCallStatus",
										"resizable" : true,
										"search" : true,
										"searchoptions" : {
											"value" : {
												"0" : " ",
												"65" : "Pending Review",
												"58" : "No Call Required",
												"204" : "Waived",
												"205" : "Completed",
												"150" : "------",
												"55" : "Margin Request Issued",
												"56" : "Margin Request Confirmed",
												"145" : "Partial Dispute",
												"146" : "Full Dispute",
												"389" : "Partial dispute & Full dispute",
												"59" : "Margin Request Received",
												"149" : "Collateral Booked"
											}
										},
										"sortable" : true,
										"stype" : "select",
										"width" : 120
									},
									{
										"align" : "left",
										"editable" : true,
										"editoptions" : {
											"value" : {
												"0" : "&nbsp;",
												"496" : "Sub Request Received",
												"497" : "Sub Request Made"
											}
										},
										"editrules" : "",
										"edittype" : "select",
										"formatter" : udfStatusFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "userDefinedCallStatus",
										"label" : "User Defined Call Status",
										"name" : "userDefinedCallStatus",
										"resizable" : true,
										"search" : true,
										"searchoptions" : {
											"value" : {
												"0" : "&nbsp;",
												"496" : "Sub Request Received",
												"497" : "Sub Request Made"
											}
										},
										"sortable" : true,
										"stype" : "select",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : eventSourceFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "eventSource",
										"label" : "Margin Type",
										"name" : "nonNet",
										"resizable" : true,
										"search" : true,
										"searchoptions" : {
											"value" : {
												"0" : " ",
												"1" : "Net",
												"2" : "Not-Net",
												"3" : "Auto-Net"
											}
										},
										"sortable" : true,
										"stype" : "select",
										"width" : 75
									},
									{
										"align" : "Center",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : tickImgFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "released",
										"label" : "RBC",
										"name" : "released",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 30
									},
									{
										"align" : "Center",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : tickImgFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "",
										"label" : "SDB",
										"name" : "sysDraftPresent",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 30
									},
									{
										"align" : "Center",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : tickImgFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "statement.clBreached",
										"label" : "CLB",
										"name" : "clBreached",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 30
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "actionId",
										"label" : "Action",
										"name" : "movementRequired",
										"resizable" : true,
										"search" : true,
										"searchoptions" : {
											"value" : {
												"0" : " ",
												"52" : "Call",
												"51" : "Recall",
												"387" : "Call & Recall",
												"53" : "Delivery",
												"54" : "Return",
												"388" : "Delivery & Return",
												"120" : "ITM No Calls",
												"121" : "OTM No Calls"
											}
										},
										"sortable" : true,
										"stype" : "select",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "currency",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementRequirement",
										"label" : "Agreement Requirement",
										"name" : "marginCall",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : true,
										"editoptions" : {
											"custom_element" : ctpyAmtElem,
											"custom_value" : ctpyAmtValue
										},
										"editrules" : "",
										"edittype" : "custom",
										"formatter" : ccyFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "marginDelvCtpy",
										"label" : "Counterparty Amount",
										"name" : "marginDelvCtpy",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : true,
										"editoptions" : {
											"custom_element" : umCtpyAmtElem,
											"custom_value" : umCtpyAmtValue
										},
										"editrules" : "",
										"edittype" : "custom",
										"formatter" : ccyFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "marginDelvCtpy",
										"label" : "Counterparty Amount Umbrella Base Ccy",
										"name" : "marginDelvCtpyUmbBaseCcy",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 150
									},
									{
										"align" : "Center",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : tickImgFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "verified",
										"label" : "CEV",
										"name" : "verified",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 30
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "currency",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.std",
										"label" : "STD Amount",
										"name" : "stdAmount",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "currency",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreedAmount",
										"label" : "Sys.Calculated Amount",
										"name" : "agreedAmount",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "currency",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "workflowProc.issuedValue",
										"label" : "Issued Value",
										"name" : "issuedValue",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "date",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "workflowProc.issueDate",
										"label" : "Issued Date",
										"name" : "issueDate",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 65
									},
									{
										"align" : "left",
										"editable" : true,
										"editoptions" : {
											"custom_element" : agreedAmountElem,
											"custom_value" : agreedAmountValue
										},
										"editrules" : "",
										"edittype" : "custom",
										"formatter" : "currency",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreedAmount",
										"label" : "User Agreed Amount",
										"name" : "userAgreedAmount",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "Center",
										"editable" : true,
										"editoptions" : {
											"custom_element" : overwriteElem,
											"custom_value" : overwriteValue,
											"value" : "true:false"
										},
										"editrules" : "",
										"edittype" : "custom",
										"formatter" : "checkbox",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "overWriteUserAgreedAmt",
										"label" : "Overwrite",
										"name" : "overwrite",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100,
										"formatoptions" : {
											disabled : false
										}
									},
									{
										"align" : "Center",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : agrBaseCcyFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.baseCurrency",
										"label" : "Agr Base Ccy",
										"name" : "currency",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 80
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : disputedAgeFmtter,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "disputeAge",
										"label" : "Dispute Age",
										"name" : "disputeAge",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 70
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "currency",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "disputeAmt",
										"label" : "Dispute Value",
										"name" : "disputedValue",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : true,
										"editoptions" : {
											"custom_element" : commentsElem,
											"custom_value" : commentsValue
										},
										"editrules" : "",
										"edittype" : "custom",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "comments",
										"label" : "Comments",
										"name" : "comments",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 110
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "currency",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "statement.totalExposure",
										"label" : "Total Exposure Amount",
										"name" : "totalExposure",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : true,
										"editoptions" : {
											"custom_element" : ctpyAmtElem,
											"custom_value" : ctpyExposureValue
										},
										"editrules" : "",
										"edittype" : "custom",
										"formatter" : "currency",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "cptyExposure",
										"label" : "Cpty Exposure",
										"name" : "cptyExposure",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "currency",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "",
										"label" : "Adjusted Collateral Value",
										"name" : "adjColValue",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.colManager",
										"label" : "Collateral Manager",
										"name" : "colManager",
										"resizable" : true,
										"search" : true,
										"searchoptions" : {
											"value" : {
												"0" : " ",
												"London Derivatives Collateral Desk   - null" : "London Derivatives Collateral Desk   - null",
												"London Derivatives Collateral  Desk - null" : "London Derivatives Collateral  Desk - null",
												"London Derivatives Collateral Desk - null" : "London Derivatives Collateral Desk - null",
												"Ben Aston - null" : "Ben Aston - null",
												"P1 Sub1 - null" : "P1 Sub1 - null",
												"OTC COLLATERAL DESK - Collateral Team" : "OTC COLLATERAL DESK - Collateral Team",
												"ABN Asset Management Ltd - null" : "ABN Asset Management Ltd - null"
											}
										},
										"sortable" : true,
										"stype" : "select",
										"width" : 120
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.reciprocity",
										"label" : "Reciprocity",
										"name" : "reciprocity",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.prinOrgHeader.shortName",
										"label" : "Prc Name",
										"name" : "principalName",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 120
									},
									{
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.agreementType",
										"label" : "Type",
										"name" : "agreementType",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : "currency",
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementRequirement",
										"label" : "Sys Requirement",
										"name" : "systemReq",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 100
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "",
										"label" : "Sys Base Ccy",
										"name" : "systemBaseCcy",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "",
										"label" : "LRFP",
										"name" : "legalFrequencyPeriod",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 40
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "",
										"label" : "LRFD",
										"name" : "legalFrequencyDays",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 40
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "",
										"label" : "Notify By",
										"name" : "notifyBy",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 70
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "",
										"label" : "Resolve By",
										"name" : "resolveBy",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 150
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "",
										"label" : "Credit Ratings",
										"name" : "creditRating",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									}, {
										"align" : "Center",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : true,
										"hidedlg" : false,
										"index" : "",
										"label" : "Event Source",
										"name" : "eventSource",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : true,
										"hidedlg" : false,
										"index" : "",
										"label" : "Init Tab",
										"name" : "eeInitTab",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : true,
										"hidedlg" : false,
										"index" : "",
										"label" : "Historical",
										"name" : "historical",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "",
										"label" : "Delivery Status",
										"name" : "deliveryStatus",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : false,
										"hidedlg" : false,
										"index" : "agreementHeader.groupId",
										"label" : "Group",
										"name" : "group",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : true,
										"stype" : "",
										"width" : 60
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : true,
										"hidedlg" : false,
										"index" : "",
										"label" : "Agreement Status",
										"name" : "agreementStatus",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : true,
										"hidedlg" : false,
										"index" : "",
										"label" : "intra Day",
										"name" : "intraDay",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									}, {
										"align" : "left",
										"editable" : false,
										"editoptions" : null,
										"editrules" : "",
										"edittype" : "",
										"formatter" : null,
										"hidden" : true,
										"hidedlg" : false,
										"index" : "",
										"label" : "MarketData Id",
										"name" : "marketDataId",
										"resizable" : true,
										"search" : false,
										"searchoptions" : null,
										"sortable" : false,
										"stype" : "",
										"width" : 100
									} ],
							"colNames" : [ " ", "WorkFlow", "External Id",
									"Agr Id", "Movement Required", "Dead Line",
									"Letter Action", "Event Date",
									"Event Date (Agreement)", "Event ID",
									"Principal Id", "Principal",
									"Counterparty Id", "Counterparty",
									"Description", "Stmt Status", "Wrk Status",
									"CA", "Call Status", "UDC Status",
									"Margin Type", "RBC", "SDB", "CLB",
									"Action", "Agreement Requirement",
									"Counterparty Amount",
									"Counterparty Amount Umbrella Base Ccy",
									"CEV", "STD Amount",
									"Sys.Calculated Amount", "Issued Value",
									"Issued Date", "User Agreed Amount",
									"Overwrite", "Agr Base Ccy", "Dispute Age",
									"Dispute Value", "Comments",
									"Total Exposure Amount", "Cpty Exposure",
									"Adjusted Collateral Value",
									"Collateral Manager", "Reciprocity",
									"Prc Name", "Type", "Sys Requirement",
									"Sys Base Ccy", "LRFP", "LRFD",
									"Notify By", "Resolve By",
									"Credit Ratings", "Event Source",
									"Init Tab", "Historical",
									"Delivery Status", "Group",
									"Agreement Status", "intra Day",
									"MarketData Id" ],
							"datatype" : "json",
							"height" : 480,
							"jsonReader" : {
								"id" : "workflowId",
								"page" : "page",
								"records" : "records",
								"repeatitems" : false,
								"root" : "items",
								"total" : "total"
							},
							"multiselect" : true,
							"pager" : "#gridPager",
							"rowList" : [ 10, 20, 30 ],
							"rowNum" : 20,
							"shrinkToFit" : false,
							"sortable" : false,
							"sortname" : "agreementHeader.id",
							"sortorder" : "Asc",
							"toolbar" : [],
							"url" : "jqGrid/ee_real_world/newData.json",
							"viewrecords" : true
						});
		reCalcGridHeight();

		function reCalcGridHeight() {
			$jqGrid.jqGrid("setGridHeight", getGridHeight());
		}
		function reCalcGridWidth() {
			$jqGrid.jqGrid("setGridWidth", $("#p4").width() - 10);
		}

		$(".ui-pg-input").keypress(function(event) {
	   		if ( ((event.which > 47) && (event.which < 58)) || (event.which == 8) ) {  
	            return true;  
	        } else {
	        	if(event.which == 13) {
	        		if($("#sp_1").text() < $(this).val()) {
	        			event.preventDefault();
	        			//$(this).val($("#sp_1").text());
	        			//$jqGrid.setGridParam('page', parseInt($("#sp_1").text()));
	        		}
	        	}
	            return false;  
	        }  
		});
		
		$(window).resize(function() {
			setTimeout(reCalcGridHeight, 500);
			setTimeout(reCalcGridWidth, 500);
		});

		// ** Save Data Filter Method
		var saveDataFilter = function() {
			if (!filterId)
				return;

			var $filter = $("#" + filterId);
			if ($filter.parent().parent().hasClass("sysFilterItems")) {
				alert("could not modify the System Filter");
				return;
			}

			var $inputs = $filter.siblings(":input");
			//				var filter = new Object();
			//				filter.id = filterId;

			var filterItems = new Array();
			var filterItem;
			$("select,:text", "#p4 .ui-search-toolbar").each(
					function(i) {
						filterItem = new Object();
						filterItem.fieldName = $(this).attr("id").replace(
								"gs_", "");

						//advanced search need matchType
						//					filterItem.filterType = "CONTAINS";
						filterItem.filterValue = $(this).val();
						filterItems.push(filterItem);

						var $input = $inputs.filter("[name='"
								+ filterItem.fieldName + "']");
						if ($input.length == 0) {
							$input = $("<input>", {
								"type" : 'hidden',
								"name" : filterItem.fieldName
							//							"value": filterItem.filterValue
							});
							$input.insertAfter($inputs.length == 0 ? $filter
									: $inputs);
						}
						$input.val(filterItem.filterValue);
					});

			sendAjaxRequest({
				method : 'updateDataFilter',
				cfgId : cfgId,
				filterId : filterId,
				filter : JSON.stringify(filterItems)
			}, function(data) {
				cfgId = data;
			});

		}

		var clearDataFilter = function() {
			var sgrid = $jqGrid[0];
			sgrid.clearToolbar();
		}

		// ** top toolbar 'Save' & 'Clear' Filter Buttons	
		//			$("#jqGrid").toolbarButtonAdd("#t_jqGrid",{
		//					caption:"",
		//					title:"Save Filters", 
		//					position:"first",
		//					align:"right", 
		//					buttonicon:"ui-icon-disk", 
		//					onClickButton: saveDataFilter 
		//				})
		//				.toolbarButtonAdd("#t_jqGrid",{
		//					caption:"",
		//					title:"Clear Fiters", 
		//					buttonicon:"ui-icon-refresh", 
		//					onClickButton: clearDataFilter 
		//				});

		// ** bottom toolbar Buttons
		// [ -- 'Nav Pagination' & 'Save Filter' & 'Clear Filter' & 'Reorder Columns' -- ]
		$jqGrid.jqGrid('navGrid', '#gridPager', {
			add : true,
			del : true,
			edit : true,
			view : true,
			search : true,
			refresh : true,
			position : 'left'
		}).jqGrid('navButtonAdd', '#gridPager', {
			caption : "save",
			title : "Save Filters",
			buttonicon : "ui-icon-disk",
			onClickButton : saveDataFilter,
			position : "last"

		}).jqGrid('navButtonAdd', '#gridPager', {
			caption : "clear",
			title : "Clear Fiters",
			buttonicon : "ui-icon-refresh",
			onClickButton : clearDataFilter,
			position : "last"

		});

		$jqGrid.jqGrid('navButtonAdd', '#gridPager', {
			caption : "columns",
			title : "Reorder Columns",
			onClickButton : function() {
				$jqGrid.jqGrid('columnChooser', {
					done : function(perm) {

						if (perm) {
							perm.shift();
							var postPerm = null;

							if (perm != gridPerm) {
								this.jqGrid("remapColumns", perm, true);
								gridPerm = perm;
								postPerm = perm;
							}

							var colModel = this.jqGrid("getGridParam",
									"colModel");
							var hiddenIds = new Array();
							for ( var i = 0; i < colModel.length; i++) {
								if (colModel[i].hidden) {
									hiddenIds.push(colModel[i].name);
								}
							}

							sendAjaxRequest({
								method : 'updateGridPro',
								cfgId : cfgId,
								hiddenIds : JSON.stringify(hiddenIds),
								perm : JSON.stringify(postPerm)
							}, function(data) {
								cfgId = data;
							});
						}
					}
				});
			}
		});

		$jqGrid.jqGrid('filterToolbar', {
			searchOnEnter : true,
			stringResult : false,
			beforeSearch : function() {
				if ($jqGrid.jqGrid("getGridParam", "datatype") != 'json') {
					$jqGrid.jqGrid("setGridParam", {
						datatype : "json"
					});
					$jqGrid.jqGrid("setGridParam", {
						url : "jqGrid/ee_real_world/newData.json"
					});
					$jqGrid.jqGrid("removePostDataItem", "filters");
					var sgrid = $jqGrid[0];
					sgrid.triggerToolbar();
					return false;
				}
			}
		});

		$jqGrid.jqGrid('setGridParam', {
			serializeGridData : function(postData) {
				//					postData.filter = "";
				return postData;
			},
			formatCell : function(rowid, cellname, value, iRow, iCol) {
				rowData = $jqGrid.jqGrid("getRowData", rowid);
			},
			//key edit select box problem
			beforeSaveCell : function(rowid, celname, value, iRow, iCol) {
				if (this.p.savedRow.length >= 1
						&& this.p.savedRow[0].v == "Completed") {

				}
			},
			afterSaveCell : function(rowid) {
				if (!$("#jqg_jqGrid_" + rowid).attr("checked"))
					$("#jqg_jqGrid_" + rowid).click().attr("checked", true);

				//test checkbox click event 	
				//$("#jqg_jqGrid_457").attr("checked",true).triggerHandler("click");

				//$("#jqg_jqGrid_457").triggerHandler("click");
				//$("#jqg_jqGrid_457").attr("checked",true);

			},
			gridComplete : function() {
				//					alert("dd");
			},
			loadComplete : function(data) {
				addChkEventTest();
				//addChkEvent();
				addTreeEvent();
			},
			loadError : function(xhr, status, error) {
				alert(error);
			}
		});

		function addChkEventTest() {
			$("#jqg_jqGrid_457").click(function() {
				log($(this).attr("id"));
			});
			$("#jqg_jqGrid_457").focus(function() {
				log($(this).attr("id"));
			});
		}

		$("#checkTest").click(function() {
			var changedArr = $jqGrid.jqGrid('getChangedCells', 'dirty');
			log(changedArr);
		});

		$("#gridBtn").click(function() {

			var col = {
				name : "agreementId",
				"sortable" : true,
				align : "left",
				"editable" : true,
				"label" : "Agr"
			};

			$jqGrid.jqGrid("setColProp", 'agreementId', {
				"sortable" : true,
				align : "left",
				"editable" : true
			});
			$jqGrid.jqGrid("hideCol", col.name);
			//				$jqGrid.jqGrid("setLabel",col.name, col.label);

		});

		//add checkBox click event
		var addChkEvent = function() {
			var multiChks = new Array();
			$("#jqGrid tbody tr").each(function(index) {
				var $multiChk = $(this).find("td:first :checkbox");
				multiChks.push($multiChk);
				$multiChk.click(function() {
					//						var numberArr = $jqGrid.jqGrid("getGridParam", "selarrrow");
					//						numberArr.push($(this).attr("id"));

					var checkedNum = 0;
					$.each(multiChks, function(i, n) {
						if (n.attr('checked')) {
							checkedNum++;
						}
					});

					actionBtnCheckRequest(checkedNum);
				});
			});
		}

		$("#cb_jqGrid").click(function() {
			if (filterId)
				actionBtnCheckRequest($(this).attr("checked") ? 2 : 0);
		})

		var actionBtnCheckRequest = function(number) {
			$("li", "#actions").hide();
			sendSyncRequest({
				method : 'showActionBtn',
				selectedItemNum : number
			}, function(data) {
				if (data) {
					var nameArr = data.split(",");
					for ( var i = 0; i < nameArr.length; i++) {
						//					                $("." + nameArr[i]).slideDown("slow");
						$("." + nameArr[i]).show("slow");
					}
				}
			}, "text", true);
		}

		function addTreeEvent() {
			$("#jqGrid .ui-icon-triangle-1-e").toggle(
					function(event) {

						var treeIds = ($treeIds[this.title] || []).join(",#");

						if ($treeIds.enable && treeIds.length != 0
								&& $("#" + treeIds).length != 0) {
							$("#" + treeIds).show();
						} else {
							createTrees(this);
						}

						$(this).removeClass("ui-icon-triangle-1-e").addClass(
								"ui-icon-triangle-1-s");
					},
					function() {

						$("#" + $treeIds[this.title].join(",#")).hide();
						$(this).removeClass("ui-icon-triangle-1-s").addClass(
								"ui-icon-triangle-1-e");

					});

		}

		function createTrees(that) {

			$.ajax({
				url : 'jqGrid/ee_real_world/treeData.json',
				type : 'GET',
				dataType : 'json',
				async : false,
				success : function(result) {
					if (sessionTimeOutCheck(result)) {
						sessionTimeOutAction();
					}
					;

					enableTreeCache(true);
					var isTickAll = $("#cb_jqGrid").attr("checked");
					$treeIds[that.title] = $.map(result.items, function(data) {
						if ($jqGrid.jqGrid('addRowData', data.workflowId, data,
								'after', that.title)) {
						
						//fix select all box checked when search fund events
						if(isTickAll) $("#jqg_jqGrid_" + data.workflowId).attr("checked",true);
							
							return data.workflowId;
						}
					});

					var originalData = $jqGrid.getGridParam('userData');

					var newData = $.extend(originalData, result.userdata);

					$jqGrid.setGridParam('userData', newData);
					addChkEvent();
				},
				error : function() {
					alert(arguments[1]);
				}
			});
		}

		function enableTreeCache(flag) {
			$treeIds.enable = flag;
		}

		var commentsFun = function(savedType) {
			sendAjaxRequest({
				method : 'saveComments',
				savedType : savedType,
				workflowId : rowData.workflowId,
				eeComments : $("#txtComments").val()

			});
			$("#dialog-comments").dialog('close');

			multiEditorEnterTrigger($("#txtComments").val());

		}

		//	save comments
		$("#dialog-comments").dialog({
			autoOpen : false,
			width : 380,
			modal : true,
			buttons : {
				'Save' : function() {
					commentsFun('COMMENT_ONLY');

				},
				'Save to Disputes' : function() {
					commentsFun('COMMENT_AND_DISPUTE');

				},
				'Save to Notes' : function() {
					commentsFun('COMMENT_AND_NOTE');

				}
			}

		});

		//	currencyExchange
		$("#dialog-ccyExchange")
				.dialog(
						{
							autoOpen : false,
							height : 350,
							width : 350,
							show : 'scale',
							hide : 'explode',
							buttons : {
								'convert' : function() {

									sendAjaxRequest(
											{
												method : 'ccyConvertor',
												originalCurrency : $(
														"select[name='originalCurrency']")
														.val(),
												originalAmount : $(
														"#_originalAmount")
														.val(),
												resultCurrency : $(
														"select[name='resultCurrency']")
														.val()

											},
											function(data) {

												if (data == "Change rate is wrong"
														|| data == "OriginalAmount is invaild") {
													$("#errorMsg").text(data);
												} else {
													$("#dialog-ccyExchange")
															.dialog('close');
													//                   				$jqGrid.setCell(rowData.workflowId,"marginDelvCtpy",data);

													//								$multiEditor.focus();

													multiEditorEnterTrigger(data);
												}
											});
								},
								'close' : function() {
									$multiEditor.focus();
									$(this).dialog('close');
								}

							}

						});

		function editFocusTrigger($elem) {
			window.setTimeout(function() {
				$elem.focus();
			}, 0);
		}

		function multiEditorEnterTrigger(data) {
			$multiEditor.val(data);
			var evt = jQuery.Event("keydown");
			evt.keyCode = $.ui.keyCode.ENTER;
			$multiEditor.trigger(evt);
		}

		function convertString2Float(val) {
			return parseFloat(val.replace(/,/g, ""));
		}

		function checkForComment(changedArr) {
			//var isMandatoryComment = <c:out value="${isMandatoryComment}"/>;
			var failureRows = new Array();
			var workflowData;

			$.each(
				changedArr,
				function(index, val) {
					workflowData = getRowData(val.id);

					if (val.comments) {
						return true;
					}

					//check margin call status whether is waived
					if (val.marginCallStatus == "Waived") {
						failureRows.push(val.id);
					}

					//check max value between 'Agreement Requirement' and 'Counterparty Amount'	marginCallStatus 
					if (true) {
						if (workflowData.movementRequiredId == 51
								|| workflowData.movementRequiredId == 52) {
							if (convertString2Float(workflowData.marginDelvCtpy) < convertString2Float(workflowData.marginCall)) {
								failureRows.push(val.id);
							}

						} else if (workflowData.movementRequiredId == 53
								|| workflowData.movementRequiredId == 54) {
							if (convertString2Float(workflowData.marginDelvCtpy) > convertString2Float(workflowData.marginCall)) {
								failureRows.push(val.id);
							}
						}
					}

				});
			if (failureRows.length > 0) {
				//TODO eligile workflow message in Message panel
				return false;
			}
			return true;
		}

		// add action event
		$("li", "#actions").click(function() {

			if ($(this).hasClass("save")) {
				enableTreeCache(false);
				var changedArr = $jqGrid.jqGrid('getChangedCells', 'dirty');

				if (!checkForComment(changedArr)) {
					alert("Comments must be populated");
					return;
				}

				$jqGrid.jqGrid("getPostData");
				$jqGrid.jqGrid("appendPostData", {
					changedArr : JSON.stringify(changedArr)
				});

				$jqGrid.trigger("reloadGrid");

			} else {

				var baseURL = $(this).attr("baseURL");
				var parameter = $(this).attr("param");

				var URL = baseURL;
				if (parameter) {
					URL = baseURL + "?";
					URL = buildURL(URL, parameter);
				}
				if ($(this).hasClass("transfer")) {
					ii = ii + 1;
					var methodName = ii % 2 == 0 ? "getHTML" : "getHTMLNext";
					$dialogtransfer.load("ajaxLoad.do", {
						method : methodName
					}, function(responseText, textStatus, XMLHttpRequest) {
						alert("load successful");
					});

					$dialogtransfer.dialog('open');
				} else if ($(this).hasClass("bulkBooking")) {
					$dialogbook.dialog('open');
				} else {

					window.location.href = "/firmament/" + URL;
				}

			}
		});

		function buildURL(URL, parameter) {
			var selectedRowIds = $jqGrid.jqGrid("getGridParam", "selarrrow");
			if (!selectedRowIds) {
				selectedRowIds = getSelectedRowIds();

			}
			var curRowData = $jqGrid.jqGrid("getRowData", selectedRowIds[0]);

			var str = parameter.split(",");

			for (i = 0; i < str.length; i++) {
				if (str[i].indexOf("=") != -1) {
					URL = URL + str[i] + "&";
				} else {
					URL = URL + str[i] + "="
							+ getParamValue(curRowData, str[i]) + "&";
				}
			}
			URL = URL.substring(0, URL.length - 1);
			return URL;
		}

		function getSelectedRowIds() {
			return $("#jqGrid input:checkbox:enabled").filter(":checked").map(
					function() {
						return $(this).attr("id").replace("jqg_jqGrid_", "");
					});
		}

		function getParamValue(obj, paramName) {
			return obj[paramName];

		}

		// West Navigation

		// ** Setup Accordion
		$accordions = $("#accordions").accordion({
			fillSpace : true
		});

		// ** Setting Sortable
		var $sortableItems = $accordions.find(".connectedSortable").sortable({
			appendTo : 'body',
			cursor : 'move',
			placeholder : 'ui-sortable-placeholder-item',
			helper : function(event) {
				return $('<div class="ui-icon ui-icon-circle-check"></div>');
			},
			//				stop: saveLayout,
			opacity : 0.5
		}).disableSelection();

		// ** save item order
		function saveLayout() {

			var idsArr = new Array();
			$sortableItems.each(function(i) {
				var idArr = $(this).find("li").map(function(index, item) {
					return $(item).attr("id");
				})
				idsArr.push(idArr.get());
			})

			sendAjaxRequest({
				method : 'updateItemPos',
				cfgId : cfgId,
				idsArray : JSON.stringify(idsArr)
			}, function(data) {
				cfgId = data;
			});
		}

		// ** drag item on accordion header
		var $accordion_headers = $("#accordions > h3");
		$accordion_headers.not("#default").droppable(
				{
					accept : "#accordions .connectedSortable li",
					hoverClass : "ui-state-highlight",
					drop : function(ev, ui) {
						var $item = $(this);
						var $list = $item.next("div")
								.find('.connectedSortable');

						ui.draggable.css("display", "");
						ui.draggable.hide('slow', function() {
							$accordions.accordion("activate",
									$accordion_headers.index($item));
							//be care of $(this), this --> draggable item
							$(this).appendTo($list).show('highlight', 2000);
						});
					}
				});

		// ** add category add, edit, del hover
		$accordion_headers
				.not("#default")
				.hover(function() {
					$(this).find("a").nextAll().show();
				}, function() {
					$(this).find("a").nextAll().hide();
				})
				.find("a")
				.nextAll()
				.click(
						function() {
							$selectedCategory = $(this).parent();
							if ($(this).hasClass("ui-icon-plusthick")) {
								clearValidationStatus();
								
								$("#itemLabel").val("");
								$("#itemDesc").val("");

								$dialogitem.dialog("option", "title",
										'New Item');
								$dialogitem.dialog("option", "buttons", {
									"Save" : addItemDialogFun,
									"Cancel" : cancelDialogFun
								});

								$dialogitem.dialog('open');
							} else if ($(this).hasClass("ui-icon-pencil")) {

								$("#categoryLabel").val(
										$selectedCategory.find("a").text());
								$("#categoryDesc").val(
										$selectedCategory.attr("title"));

								$dialogcategory.dialog("option", "title",
										'Category Edit');
								$dialogcategory.dialog("option", "buttons", {
									"Save" : editCategoryDialogFun,
									"Cancel" : cancelDialogFun
								});
								$dialogcategory.dialog('open');

							} else {

								if ($selectedCategory.next().children('ul')
										.children().length == 0) {
									$dialogConfirm.dialog("option", "title",
											'Category Delete');
									$dialogConfirm
											.dialog(
													"option",
													"buttons",
													{
														"Delete" : delCategoryDialogFun,
														"Cancel" : cancelDialogFun
													});
									$dialogConfirm.dialog('open');
								} else {
									alert("please delete items belong to category first");
								}
							}
							//				event.stopImmediatePropagation();
							return false;
						});

		// ** add item edit & del behavior
		bindDefaultFilterItemEvent($(".sysFilterItems li", "#accordions"));
		bindFilterItemEvent($(".connectedSortable li", "#accordions"));

		// ** Accordion Item Click Event
		function bindDefaultFilterItemEvent(obj) {
			obj.hover(function() {
				$(this).addClass("item-hover");
			}, function() {
				$(this).removeClass("item-hover")
			}).click(itemClickFun);
		}

		function bindFilterItemEvent(obj) {
			obj.hover(function() {
				$(this).addClass("item-hover").find("a").show();
			}, function() {
				$(this).removeClass("item-hover").find("a").hide();
			}).click(itemClickFun).find("a").click(itemModifiedFun);
		}

		function itemClickFun() {
			
			//test
			var changedArr = $jqGrid.jqGrid('getChangedCells', 'dirty');
			
			var rData = getRowData(changedArr[0].id);
			
			$(this).addClass("item-click").siblings().removeClass("item-click");

			if ($jqGrid.jqGrid("getGridParam", "datatype") != 'json') {
				$jqGrid.jqGrid("setGridParam", {
					datatype : "json"
				});
			}
			enableTreeCache(false);
			clearToolbarValue();
			//				clearDataFilter();

			filterId = $(this).attr("filter");

			$(this).find("input:hidden").each(function(i) {

				$("#gs_" + $(this).attr("name")).val($(this).val());
			});

			var tabPageNum = $(this).find("input[name='tabPage']").val();
			if (tabPageNum) {
				$jqGrid.jqGrid("appendPostData", {
					tabPage : tabPageNum
				});
			} else {
				$jqGrid.jqGrid("removePostDataItem", "tabPage");

			}

			var sgrid = $jqGrid[0];
			sgrid.triggerToolbar();

		}

		function itemModifiedFun() {

			$selectedItem = $(this).parent();
			if ($(this).hasClass("pencil")) {

				$selectedItem.removeClass("ui-state-default");
				$sysIcons.find("li").removeClass("ui-selected").each(
						function(i) {
							if ($(this).attr("title") == $selectedItem
									.attr("class")) {
								$(this).addClass("ui-selected");
								return false;
							}
						});

				$("#itemLabel").val($selectedItem.find("font").text());
				$("#itemDesc").val($selectedItem.attr("title"));

				$dialogitem.dialog("option", "title", 'Item Edit');
				$dialogitem.dialog("option", "buttons", {
					"Save" : editItemDialogFun,
					"Cancel" : cancelDialogFun
				});
				//$dialogitem.dialog( "option", "buttons", [ { text: "Save", click: editItemDialogFun }, { text: "Cancel", click: cancelDialogFun } ] );
				$dialogitem.dialog('open');
			} else {
				$dialogConfirm.dialog("option", "title", 'Item Delete');
				$dialogConfirm.dialog("option", "buttons", {
					"Delete" : delItemDialogFun,
					"Cancel" : cancelDialogFun
				});
				//$dialogConfirm.dialog( "option", "buttons", [ { text: "Delete", click: delItemDialogFun }, { text: "Cancel", click: cancelDialogFun } ] );
				$dialogConfirm.dialog('open');
			}
			return false;

		}

		function clearToolbarValue() {

			$(".ui-search-toolbar :text", "#p4").each(function(i) {
				$(this).val("");
			});

			$(".ui-search-toolbar select", "#p4").each(function(i) {
				$(this).get(0).selectedIndex = 0;

				//$(this).find("option").each(function(index) {
				//	if(index===0) { this.selected = true; }
				//});
			});

		}

		var cancelDialogFun = function() {
			$(this).dialog('close');
		}
		window.hello = function() {
			alert("hello");
		}
		var addCategoryDialogFun = function() {

		}

		var editCategoryDialogFun = function() {
			//ajax save Data
			var bValid = true;

			var category = new Object();
			category.id = $selectedCategory.attr("id");
			category.label = $("#categoryLabel").val();
			category.desc = $("#categoryDesc").val();

			if (bValid) {

				sendAjaxRequest({
					method : 'updateCatagory',
					cfgId : cfgId,
					category : JSON.stringify(category)
				}, function(result) {
					cfgId = result;
				});

				$(this).dialog('close');

				$selectedCategory.attr("title", category.desc);
				$selectedCategory.find("a").text(category.label);

			}

		}

		var delCategoryDialogFun = function() {
			sendAjaxRequest({
				method : 'delCatagory',
				cfgId : cfgId,
				categoryId : $selectedCategory.attr("id")
			}, function(data) {
				cfgId = data;
			});

			$selectedItem.remove();

			$(this).dialog('close');
		}

		function clearValidationStatus() {
			$("form.validationform .status").html("&nbsp;").removeClass("checked");
		}
		
		var addItemDialogFun = function() {
			var bValid = $("#signupform").validate().form();

			var accordionItem = new Object();
			accordionItem.label = $("#itemLabel").val();
			accordionItem.desc = $("#itemDesc").val();
			accordionItem.icon = $sysIcons.find(".ui-selected").attr("title");

			var $copyItem = $(".sysFilterItems li:first", "#accordions")
					.clone().find("input[name='tabPage']").remove().end().find(
							"b").text("").end();

			if (bValid) {

				sendSyncRequest({
					method : 'createItem',
					cfgId : cfgId,
					categoryId : $selectedCategory.attr("id"),
					item : JSON.stringify(accordionItem)
				}, function(result) {
					cfgId = result.id;
					filterId = result.dataFilterId;
					$copyItem.attr("id", result.itemId).attr("filter",
							result.dataFilterId);
					$copyItem.find(":hidden:first").attr("id",
							result.dataFilterId);
				});

				$(this).dialog('close');

			}

			$copyItem.appendTo($selectedCategory.next().children("ul")).attr(
					"class", accordionItem.icon).attr("title",
					accordionItem.desc).find("font").text(accordionItem.label);

			$copyItem.addClass("item-click").siblings().removeClass(
					"item-click");
			bindFilterItemEvent($copyItem);

			//				clearToolbarValue();
			clearDataFilter();
		}

		var editItemDialogFun = function() {
			//ajax save Data
			var bValid = true;

			var accordionItem = new Object();
			accordionItem.id = $selectedItem.attr("id");
			accordionItem.label = $("#itemLabel").val();
			accordionItem.desc = $("#itemDesc").val();
			accordionItem.icon = $sysIcons.find(".ui-selected").attr("title");

			if (bValid) {

				sendAjaxRequest({
					method : 'updateItem',
					cfgId : cfgId,
					item : JSON.stringify(accordionItem)
				}, function(result) {
					cfgId = result;
				});

				$(this).dialog('close');

				$selectedItem.attr("class", accordionItem.icon);
				$selectedItem.attr("title", accordionItem.desc);
				$selectedItem.find("font").text(accordionItem.label);

			}
		}

		var delItemDialogFun = function() {
			sendAjaxRequest({
				method : 'delItem',
				cfgId : cfgId,
				categoryId : $selectedItem.parent().parent().prev().attr("id"),
				itemId : $selectedItem.attr("id")
			}, function(data) {
				cfgId = data;
			});

			$selectedItem.remove();

			$(this).dialog('close');
		}

		// ** add item edit & del dialog
		var $dialogConfirm = $("#dialog-confirm").dialog({
			autoOpen : false,
			resizable : false,
			height : 140,
			modal : true
		//				buttons: {
		//					'Delete': delItemDialogFun,
		//					Cancel: cancelDialogFun
		//				}
		});

		var $dialogtransfer = $("#dialog-transfer").dialog({
			autoOpen : false,
			height : 500,
			width : 800,
			show : 'scale',
			hide : 'explode',
			modal : true,
			buttons : {
				'Save' : function() {
					alert("save");
				},
				Cancel : function() {
					alert('cancel');
				}
			}
		});

		var $dialogbook = $("#dialog-book").dialog({
			autoOpen : false,
			height : 500,
			width : 1024,
			show : 'scale',
			hide : 'explode',
			modal : true,
			buttons : {
				'Save' : function() {
					alert("save");
				},
				Cancel : function() {
					alert('cancel');
				}
			}
		});

		var $dialogcategory = $("#dialog-category").dialog({
			autoOpen : false,
			height : 250,
			width : 350,
			show : 'scale',
			hide : 'explode',
			modal : true
		//				buttons: {
		//					'Save': editDialogItemFun,
		//					Cancel: cancelDialogFun
		//				},
		});

		var $dialogitem = $("#dialog-item").dialog({
			autoOpen : false,
			height : 250,
			width : 450,
			show : 'scale',
			hide : 'explode',
			modal : true
		//				buttons: {
		//					'Save': editDialogItemFun,
		//					Cancel: cancelDialogFun
		//				},
		});

	});

	
	datePick = function(elem) {
		jQuery(elem).datepicker({
			showAnim : 'show'
		});
	}

	autoComplete = function(elem) {
		var availableTags = [ "abc,abc", "abcd, ef", "abg,  hijk", "ablm , nop", "abkist,", ",uvwxyz", "abcef" ];
		$(elem).autocomplete({
			source : function(request, response) {
				// delegate back to autocomplete, but extract the last term
				response(jQuery.ui.autocomplete.filter(availableTags,
						extractLast(request.term)));
			},
			search : function() {
				// custom minLength
				var term = extractLast(this.value);
				if (term.length < 2) {
					return false;
				}
			},
			focus : function(e, i) {
				// prevent value inserted on focus
				return false;
			},
			select : function(event, ui) {
				var terms = split( this.value );
				// remove the current input
				terms.pop();
				$.each(terms, function(index, value) {
					terms[index] = value.trim();
				});
				
				if(ui.item.value.indexOf(",") != -1) ui.item.value = "'" + ui.item.value + "'";
				
				if(jQuery.inArray(ui.item.value, terms) !== -1) {
					return false;
				}
				// add the selected item
				terms.push( ui.item.value );
				// add placeholder to get the comma-and-space at the end
				terms.push("");
				this.value = terms.join( ", " );
				
				return false;
			}
		});
	}
	autoCompleteRemote = function(elem) {
		// don't navigate away from the field on tab when selecting an item
		$(elem).bind(
				"keydown",
				function(event) {
					if (event.keyCode === $.ui.keyCode.TAB
							&& $(this).data("autocomplete").menu.active) {
						event.preventDefault();
					}
				}).autocomplete({
			source : function(request, response) {
				sendSyncRequest({
					method : 'searchPric',
					term : extractLast(request.term)
				}, response);
			},
			search : function() {
				// custom minLength
				var term = extractLast(this.value);
				if (term.length < 2) {
					return false;
				}
			},
			focus : function(e, i) {
				// prevent value inserted on focus
				return false;
			},
			select : function(event, ui) {
				var terms = split(this.value);
				// remove the current input
				terms.pop();
				// add the selected item
				terms.push(ui.item.value);
				// add placeholder to get the comma-and-space at the end
				terms.push("");
				this.value = terms.join(", ");
				return false;
			}
		});
	}

	function split(val) {
		//return val.split(/,\s*/);
		return val.split(/,(?=(?:[^']|'[^']*')*$)/g);
	}

	function extractLast(term) {
		return split(term).pop().trim();
	}
	
	function showMsg(message, success) {
		if(!success) {
			jQuery( "<div/>" ).text(new Date().toLocaleString() +  " :    " + message).addClass("failureLog").prependTo("#log");
		} else {
			// don't show the log message in this period
			jQuery( "<div/>" ).text(new Date().toLocaleString() + " :    " + message).addClass("successLog").prependTo("#log");
		}
		jQuery( "#log" ).attr( "scrollTop", 0 );
	}

	function sendAjaxRequest(data, callback) {
		$.get("jGrid/viewPage.do", data, function(result) {
			result = $.parseJSON(result);
			
			if(!sessionTimeOutCheck(result)){
        		if(result.message)  {
        			showMsg(result.message, result.success);
        		}
        		
        		if(result.success) {
        			callback(result.data);
        		}
        	}
			
		});
	}

	function sendSyncRequest(data, callback, dtype, sync) {
		if (!dtype) dtype = 'json';
		if (!sync) sync = false;
		$.ajax({
			url : 'jGrid/viewPage.do',
			type : 'GET',
			dataType : dtype,
			data : data,
			async : sync,
			success : function(result) {
				if(!sessionTimeOutCheck(result)){
	        		if(result.message)  {
	        			showMsg(result.message, result.success);
	        		}
	        		
	        		if(result.success) {
	        			callback(result.data);
	        		}
	        	}
				
			},
			error : function() {
				alert(arguments[1]);

			}
		});
	}

	function sessionTimeOutCheck(result) {
		var reg = /<html>/ig;
		var isExpired = reg.test(result);
		if (isExpired) {
			sessionTimeOutAction();
		}

		return isExpired;
	}

	function sessionTimeOutAction() {
		window.alert("Your session has expired, please login again.");
		document.location = "/blank.jsp";
	}

	jQuery(function() {
		// validate signup form on keyup and submit
		var validator = $("#signupform").validate({
			rules : {
				itemLabel : {
					required : true,
					minlength : 2
				},
				itemDesc : "required"
			},
			messages : {
				itemLabel : "Enter your item Name",
				itemDesc : "Enter your item Description"
			},
			// the errorPlacement has to take the table layout into account
			errorPlacement : function(error, element) {
				error.appendTo(element.parent().next());
			},
			// specifying a submitHandler prevents the default submit, good for the demo
			submitHandler : function() {
				alert("submitted!");
			},
			// set this class to error-labels to indicate valid fields
			success : function(label) {
				// set &nbsp; as text for IE
				label.html("&nbsp;").addClass("checked");
			}
		});

	});
</script>
	</head>
	<body>
		<div id="loading">Loading content, please wait..<img src="jQuery_validation/images/loading.gif" alt="loading.." /></div>
		<div id="dialog-transfer" title="Transfer Page">
		</div>

		<div id="dialog-book" title="Bulk Book">
		</div>

		<div id="dialog-ccyExchange" title="currencyExchange">
			<select name="originalCurrency">
				<option value="23">AED</option>
				<option value="24">AFA</option>
				<option value="25">ALL</option>
				<option value="165">USD</option>
				<option value="26">ANG</option>
				<option value="27">AOA</option>
			</select>
			<br />
			
			<textarea id="_originalAmount" cols="20" rows="1"
				style="overflow-y: auto;"></textarea>
			<br />

			<select name="resultCurrency">
				<option value="23">AED</option>
				<option value="24">AFA</option>
				<option value="25">ALL</option>
				<option value="165">USD</option>
				<option value="26">ANG</option>
				<option value="27">AOA</option>
			</select>

		</div>

		<div id="dialog-comments" title="Save to">
			<textarea cols="40" rows="3" id="txtComments" maxLength="4000"
				style=""overflow-y:auto;">
			</textarea>
		</div>

		<div id="dialog-category" title="Category Edit">
			<p class="validateTips">
				All form fields are required.
			</p>
			<br />
			<form>
				<label>
					Name
				</label>
				<input type="text" id="categoryLabel" class="ui-widget-content" />
				<br />
				<label>
					Description
				</label>
				<input type="text" id="categoryDesc" class="ui-widget-content" />
				<br />
			</form>
			<br />
		</div>
		<div id="dialog-item" title="Item Edit">
			<p class="validateTips">
				All form fields are required.
			</p>
			<br />
			
			<form id="signupform" class="validationform" autocomplete="off" method="get" action="">
	  		  <table>
		  		  <tr>
		  		  	<td class="label"><label id="litemLabel" for="itemLabel">Name</label></td>
		  		  	<td class="field"><input id="itemLabel" name="itemLabel" type="text" value="" maxlength="100" /></td>
		  		  	<td class="status"></td>
		  		  </tr>
		  		  <tr>
		  			<td class="label"><label id="litemDesc" for="itemDesc">Description</label></td>
		  			<td class="field"><input id="itemDesc" name="itemDesc" type="text" value="" maxlength="100" /></td>
		  			<td class="status"></td>
		  		  </tr>
		  		  <tr>
		  			<td class="label"><label id="litemIcon" for="itemIcon">Icon</label></td>
		  			<td class="field">
		  				<ul id="sysIcons">
							<li class="iCall" title="iCall">
								<span class="item_bg_position"></span>
							</li>
							<li class="iReCall" title="iReCall">
								<span class="item_bg_position"></span>
							</li>
							<li class="iDelivery" title="iDelivery">
								<span class="item_bg_position"></span>
							</li>
							<li class="iReturn" title="iReturn">
								<span class="item_bg_position"></span>
							</li>
							<li class="iIssued" title="iIssued">
								<span class="item_bg_position"></span>
							</li>
						</ul>
		  			</td>
		  			<td class="status"></td>
		  		  </tr>
	  		  </table>
          </form>
			
		</div>
		<div id="dialog-confirm" title="Confirm">
			<p>
				<span class="ui-icon ui-icon-alert"
					style="float: left; margin: 0 7px 20px 0;"></span>The item will be
				permanently deleted and cannot be recovered. Are you sure?
			</p>
		</div>
		<div class="ui-layout-west" style="overflow: hidden">
			<div class="header ui-widget-header">
				Navigation
				<span id="saveOrderIcon" class="ui-icon ui-icon-disk"
					title="Save Item Order"></span>
			</div>
			<div class="content">
				<div id="accordions">
					<c:forEach items="${wrapper.categories}" var="category">
						<h3 id="${category.id }" title="${category.desc}">
							<a href="#">${category.label }</a>
							<span class="ui-icon ui-icon-plusthick" style="left: 13em"></span>
							<span class="ui-icon ui-icon-pencil" style="left: 14.5em"></span>
							<span class="ui-icon ui-icon-closethick" style="left: 16em"></span>
						</h3>
						<div style="padding: 0; border: none">
							<%--                            <ul class='<c:if test="${category.id ne 'default'}">connectedSortable </c:if> ui-helper-reset'>	--%>
							<ul
								class='<c:choose><c:when test="${category.id ne 'default'}">connectedSortable</c:when><c:otherwise>sysFilterItems</c:otherwise></c:choose> ui-helper-reset'>
								<c:forEach items="${category.items.item}" var="item">
									<c:set var="filterName" value="${item.dataFilterRef}" />
									<li id="${item.id }" class="${item.icon }" title="${item.desc}"
										filter="${filterName}">
										<input type="hidden" id="${filterName}" />
										<c:forEach
											items="${(wrapper.dataFilterMap[filterName]).dataFilterItem}"
											var="filterItem">
											<input type="hidden" name="${filterItem.fieldName}"
												value="${filterItem.filterValue}" />
										</c:forEach>
										<span class="item_bg_position"></span>
										<font style="FONT-SIZE: 10px; *FONT-SIZE: 10px;"> ${item.label } </font>
										<b>(10)</b>
										<a href="javascript:void(0)" class="icon-size cross"></a>
										<a href="javascript:void(0)" class="icon-size pencil"></a>
									</li>
								</c:forEach>
							</ul>
						</div>
					</c:forEach>
				</div>
			</div>
		</div>
		<div class="ui-layout-east">
			<div class="header ui-widget-header">
				Actions
			</div>
			<div class="contents">
				<ul style="list-style-type: none" id="actions">
					<c:forEach items="${wrapper.actionBtns}" var="actionBtn">
						<li class="${actionBtn.icon}" title="${actionBtn.desc}"
							baseURL="${actionBtn.baseURL}" param="${actionBtn.params}"
							style="cursor: pointer; display: none;">
							<span class="item_bg_position"></span>
						</li>
					</c:forEach>
				</ul>
			</div>
		</div>
		<div class="ui-layout-north"
			onmouseover="outerLayout.allowOverflow('north')"
			onmouseout="outerLayout.resetOverflow(this)"
			style="overflow: hidden;">
			<div class="top-header">
			</div>
			<ul class="toolbar">
				<li id="tbarToggleNorth" class="first">
					<span></span>Toggle NORTH
				</li>
				<li id="tbarOpenSouth">
					<span></span>Open SOUTH
				</li>
				<li id="tbarCloseSouth">
					<span></span>Close SOUTH
				</li>
				<li id="tbarPinWest">
					<span></span>Pin/Unpin WEST
				</li>
				<li id="tbarPinEast" class="last">
					<span></span>Pin/Unpin EAST
				</li>
			</ul>
		</div>
		<div class="ui-layout-south">
			<div class="footer ui-widget-header">
				<table>
					<tr>
						<td>
							Powered by Lombard Risk
						</td>
						<td>
							Organisation :
						</td>
						<td>
							Region :
						</td>
						<td>
							Group :
						</td>
					</tr>
				</table>
			</div>
		</div>

		<div id="mainContent" style="overflow: hidden">
			<div class="main-item" id="p3">
				<div class="item-header">
					Message
				</div>
				<div class="item-content" style="height: 128px; overflow-y: auto">
					<div>
						<h3>
							Error Message
						</h3>
						<div id="log"></div>
						<input type="button" id="newRow" value="Add a new row" />
						<input type="button" id="showRow" value="show a new row" />
						<input type="button" id="hideRow" value="Hide a new row" />
						<input type="button" id="gridBtn" value="change grid cfg" />
						<input type="button" id="test" value="click" />
						<input type="button" id="test2" value="click" onclick="hello()" />
						<input type="button" id="checkTest" value="checkTest" />
						<input type="text" id="keyTest" value="10" />
						
					</div>
				</div>
			</div>
			<div class="main-item" id="p4">
				<div class="item-header">
					External Exposure
				</div>
				<div class="item-content">
					<table id="jqGrid">
					</table>
					<div id="gridPager">
					</div>
				</div>
			</div>
		</div>
		<script type="text/javascript" language="JavaScript">
	$(function() {

		function clourse() {
			alert("hello");
		}

		$('#keyTest').live('keypress', function(e) {
			if (e.keyCode == 13) {
				alert("key up");
			}
		});

		$("#test2").click(function() {

			//					$('#keyTest').trigger("keypress", [{
			//					  	keyCode:13
			//					}]);

			//					$('#keyTest').val('value').trigger( "keypress", [13] ); 

			//					var evt = jQuery.Event("keypress");
			//					//evt.which = 13;
			//					evt.keyCode = 13;
			//					$("#keyTest").trigger(evt);

			var evt = jQuery.Event("keypress");
			evt.keyCode = $.ui.keyCode.ENTER;
			$("#keyTest").trigger(evt);

		})


		$("#tbarPinEast").click(getHeightLog);

		//resizeHeight();
		$(window).resize(function() {

			//setHeight();
			//getHeightLog();
		});

	});

	function resizeHeight() {
		getHeightLog();

		setHeight();

		getHeightLog();
	}

	function getGridHeight() {
		var calcValue = $("#mainContent").height() - $("#p3").outerHeight(true)
				- $("#p4 .item-header").outerHeight(true) - 118;
		return calcValue > 0 ? calcValue : 10;
	}

	function setHeight() {
		$("#p4").height(
				$("#mainContent").height() - $("#p3").outerHeight(true) - 15);
	}

	function getHeightLog() {
		log("-------------------------------------------");
		log("top height: " + $("#mainContent").height());
		log("first outer height: " + $("#p3").outerHeight(true));
		//log("first height: " + $("#p3").innerHeight());
		//log("first item height: "  + $("#p3 .item-header").outerHeight(true));
		log("second outer height: " + $("#p4").outerHeight(true));
		//log("second height: "  + $("#p4").innerHeight());
		log("second item height: " + $("#p4 .item-header").outerHeight(true));
		log("calc grid height: "
				+ ($("#mainContent").height() - $("#p3").outerHeight(true) - $(
						"#p4 .item-header").outerHeight(true)));
		log("grid height: " + getGridHeight());
		log("gid width: " + $("#p4").width());

		//jQuery("#jqGrid").jqGrid("setGridWidth", $("#p4").width() - 10);
	}

	function log(msg) {
		console.log(msg);
	}
</script>
	</body>
</html>
